//分类状态管理器
import { getCategories, getCategoriesCascader } from '@/apis/category'

const state = {
  categories: {
    categories: [],
    hierarchy: {}
  },
  cascader:{}
}

const mutations = {
  //存放扁平化数据
  setCategories(state, newCategories) {
    state.categories = newCategories
  },
  //存放级联选择器数据
  setCascader(state, newCascader) {
    state.cascader = newCascader
  }
}

const actions = {
  //获取扁平化数据
  async getCategoriesOn(context) {
    const res = await getCategories()
    context.commit('setCategories', res.data)
  },

  //获取级联选择器数据
  async getCascaderOn(context) {
    const res = await getCategoriesCascader()
    context.commit('setCascader', res.data)
  },

  // 初始化分类相关数据（进入项目时调用）
  async initCategoryOn({ dispatch }) {
    await Promise.all([
      dispatch('getCategoriesOn'),
      dispatch('getCascaderOn')
    ])
  }

}

const getters = {
  // 根据parentId获取子菜单
  getChildrenByParentId: (state) => (parentId) => {
    return state.categories.categories.filter(category => category.parentId === parentId);
  },

  // 获取所有一级分类
  getFirstLevelCategories: (state) => {
    return state.categories.filter(category => category.level === 1);
  },

  // 获取某个分类的完整路径（父子关系）
  getCategoryPath: (state) => (categoryId) => {
    const path = [];
    let current = state.categories.find(cat => cat.categoryId === categoryId);

    while (current) {
      path.unshift(current);
      if (current.parentId === 0) break;
      current = state.categories.find(cat => cat.categoryId === current.parentId);
    }
    return path;
  }
};

export default {
  namespaced: true,//开启命名空间
  state,
  mutations,
  actions,
  getters
} 